//
//  FCLQueue.m
//  FCLCommon
//
//  Created by arden on 11/24/11.
//  Copyright 2011 Fried Chicken Legs. All rights reserved.
//

#import "FCLQueue.h"


@implementation FCLQueue

@synthesize maxSize;
@synthesize forceEnqueue;

-(id) initWithCapacity: (NSInteger) capacity
{
	if(nil == (self =[super init]))
	{
		return nil;
	}
	
	if(capacity<=0)
	{
		return nil;
	}
	forceEnqueue =true;
	currentIndex=0;
	maxSize = capacity;
	
	data = malloc(maxSize*sizeof(id));
	return self;
}

-(void) enqueue:(id) obj
{
	if( maxSize > currentIndex)
	{
		data[currentIndex] = obj;
		currentIndex++;
	}
	else {
		if(forceEnqueue)
		{
			[data[0] autorelease];
			for(int i=0;i<maxSize-1;i++)
			{
				data[i]=data[i+1];
			}
			data[maxSize-1] = obj;
		}
		else {
			@throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"equeue is full" userInfo:nil];
			return;
		}

	}
}

-(id) dequeue
{
	id obj = nil;
	if(currentIndex>0)
	{
		obj = data[currentIndex-1];
		for(int i=0; i< currentIndex-1;i++)
		{
			data[i] =data[i+1];
		}
		[data[currentIndex-1] autorelease];
		data[currentIndex-1]=nil;
		currentIndex--;
	}
	
	return obj;
}

-(int) count;
{
	return currentIndex;
}

-(void) clear
{
	free(data);
	[super dealloc];
}

//
// NSFastEnumeration protocol
//
-(NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state 
								  objects:(id *)stackbuf 
									count:(NSUInteger)len
{
	return 0;
}

@end



/*
 VERSION HISTORY
 Author  Date        Comments
 arden   11/24/2011  initial version
 */

